﻿using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Options;
using Yz.Base;
using Yz.Base.Config;
using Yz.Base.Enums;
using Yz.Core.Tools;

namespace Yz.ApiService.Controllers
{
    [Route("api/")]
    [ApiController]
    public class BaseApiController : ControllerBase
    {
        #region 注入
        public IOptions<WebConfig> _optionWebConfig { get; set; }
        public IHttpContextAccessor _httpContextAccessor { get; set; }
        public IMapper _mapper { get; set; }
        protected WebConfig _webConfig => _optionWebConfig.Value;
        #endregion
        #region 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="npoiExcel"></param>
        /// <returns></returns>
        protected FileResult ExportExcel(NPOIExcel npoiExcel)
        {
            string sysName = _webConfig.SysName;
            MemoryStream stream = YzNPOI.ExportExcel(npoiExcel);
            var provider = new FileExtensionContentTypeProvider();
            string fileExt = "";
            if (npoiExcel.ExcelType == ExcelType.Xlsx)
            {
                fileExt = ExcelSuffix.Xlsx;
            }
            else
            {
                fileExt = ExcelSuffix.Xls;
            }
            npoiExcel.ExcelName = npoiExcel.ExcelName.Substring(0, npoiExcel.ExcelName.LastIndexOf("."));
            npoiExcel.ExcelName += fileExt;
            var contentType = provider.Mappings[fileExt];
            Response.Headers.Append("fileName", npoiExcel.ExcelName);
            Response.Headers.Append("Content-Disposition", "attachment; filename=" + npoiExcel.ExcelName);
            //支持跨域时可以通过axios等http库获取到在header中的数据
            //Response.Headers.Add("Access-Control-Expose-Headers", "fileName");
            return File(stream.ToArray(), contentType, npoiExcel.ExcelName);
        }
        #endregion
    }
}
